package com.summer.campussct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.summer.campussct.mapper.VehicleAuditMapper;
import com.summer.campussct.mapper.VehiclePublishMapper;
import com.summer.campussct.pojo.VehicleOrder;
import com.summer.campussct.mapper.VehicleOrderMapper;
import com.summer.campussct.pojo.VehiclePublish;
import com.summer.campussct.pojo.dto.OrderDto;
import com.summer.campussct.pojo.dto.RestResult;
import com.summer.campussct.service.IVehicleOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.campussct.utils.UserIdHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Mr.Chen
 * @since 2024-05-15
 */
@Service
public class VehicleOrderServiceImpl extends ServiceImpl<VehicleOrderMapper, VehicleOrder> implements IVehicleOrderService {

    @Resource
    private VehicleAuditMapper vehicleAuditMapper;

    @Resource
    private VehiclePublishMapper vehiclePublishMapper;

    @Resource
    private VehicleOrderMapper vehicleOrderMapper;

    @Override
    @Transactional
    public RestResult createOrder(VehicleOrder vehicleOrder) {
        // 设置查询车辆信息
        VehiclePublish vehiclePublish = vehiclePublishMapper.selectOne(new LambdaQueryWrapper<VehiclePublish>()
                .select(VehiclePublish::getOrderPrice, VehiclePublish::getUid)
                .eq(VehiclePublish::getVid, vehicleOrder.getVid()));

        // 用户不能订购自己发布的车辆
        if (UserIdHolder.getId() == vehiclePublish.getUid()){
            return RestResult.error("不能订购自己发布的车辆");
        }

        // 修改audit和publish的发布状态为30003
        int auditSuccess = vehicleAuditMapper.modifyPublishState(30003, vehicleOrder.getVid());
        if (auditSuccess == 0) throw new RuntimeException("创建订单失败：无法修改审核状态");
        int publishSuccess = vehiclePublishMapper.modifyPublishState(30003, vehicleOrder.getVid());
        if (publishSuccess == 0) throw new RuntimeException("创建订单失败：无法修改发布状态");

        BigDecimal orderPrice = vehiclePublish.getOrderPrice();
        if (orderPrice == null) throw new RuntimeException("创建订单失败：无法获取订单金额");
        vehicleOrder.setOrderPrice(orderPrice);

        // 创建订单
        if (!this.save(vehicleOrder)) {
            throw new RuntimeException("创建订单失败");
        }
        return RestResult.success(vehicleOrder.getId());
    }

    @Override
    public RestResult payDetails(long id) {
        // 查询订单(将查询条件带上uid：只有自己才能查询自己的订单)
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderPrice, VehicleOrder::getCreateTime)
                .eq(VehicleOrder::getOrderStatus, 40001)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        // 封装dto
        OrderDto orderDto = new OrderDto();
        orderDto.setOrderPrice(vehicleOrder.getOrderPrice());
        // 创建时间+10分钟 = 支付截至时间
        orderDto.setPayEndTime(vehicleOrder.getCreateTime().plusMinutes(10));
        return RestResult.success(orderDto);
    }

    @Override
    public RestResult getOrderList(long uid, Integer orderStatus) {
        List<OrderDto> orderDtoList = vehicleOrderMapper.getOrderListByUid(uid, orderStatus);
        for (OrderDto orderDto : orderDtoList) {
            // 设置付款到期时间，过期了或不为待支付状态则为null
            if (orderDto.getOrderStatus() == 40001){
                LocalDateTime createTime = orderDto.getCreateTime();
                orderDto.setPayEndTime(createTime.plusMinutes(10));
            }
        }
        return RestResult.success(orderDtoList);
    }

    @Override
    public RestResult paySuccess(long id) {
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        // 异常处理：待支付状态才能支付
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40001) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40002)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改支付状态失败");
        }
        return RestResult.success();
    }

    @Override
    @Transactional
    public RestResult cancelOrder(long id) {
        // 异常处理: 待支付才能取消；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus, VehicleOrder::getVid)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40001) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }


        // 将两个表的发布状态设置为已发布
        int auditSuccess = vehicleAuditMapper.modifyPublishState(30002, vehicleOrder.getVid());
        if (auditSuccess == 0) throw new RuntimeException("修改支付状态失败：无法修改审核状态");
        int publishSuccess = vehiclePublishMapper.modifyPublishState(30002, vehicleOrder.getVid());
        if (publishSuccess == 0) throw new RuntimeException("修改支付状态失败：无法修改发布状态");

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40003)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改支付状态失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult finishOrder(long id) {
        // 异常处理: 进行中才能点击完成交易；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus, VehicleOrder::getUid)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40002) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40006)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改订单状态失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult refundOrder(long id) {
        // 异常处理: 进行中才能点击退款；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40002) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40004)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改订单状态失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult cancelRefundOrder(long id) {
        // 异常处理: 退款中才能点击取消退款；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40004) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40002)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改订单状态失败");
        }
        return RestResult.success();
    }


    @Override
    @Transactional
    public RestResult agreeRefundOrder(long id) {
        // 异常处理: 退款中才能点击同意；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        if (vehicleOrder == null || vehicleOrder.getOrderStatus() != 40004) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        // 将车辆发布状态改为已发布
        int auditSuccess = vehicleAuditMapper.modifyPublishState(30002, vehicleOrder.getVid());
        if (auditSuccess == 0) throw new RuntimeException("同意退款失败：无法修改审核状态");
        int publishSuccess = vehiclePublishMapper.modifyPublishState(30002, vehicleOrder.getVid());
        if (publishSuccess == 0) throw new RuntimeException("同意退款失败：无法修改发布状态");

        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getOrderStatus, 40005)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("修改订单状态失败");
        }
        return RestResult.success();
    }

    @Override
    @Transactional
    public RestResult deleteOrder(long id) {
        // 异常处理: 已取消、已完成或退款成功才能删除；权限认证：只有订单用户能操作
        VehicleOrder vehicleOrder = getOne(new LambdaQueryWrapper<VehicleOrder>()
                .select(VehicleOrder::getOrderStatus, VehicleOrder::getVid)
                .eq(VehicleOrder::getId, id)
                .eq(VehicleOrder::getUid, UserIdHolder.getId()));
        Set<Integer> statusSet = new HashSet<>(3);
        statusSet.add(40003);
        statusSet.add(40005);
        statusSet.add(40006);
        if (vehicleOrder == null || !statusSet.contains(vehicleOrder.getOrderStatus())) {
            throw new RuntimeException("订单不存在或订单状态异常");
        }

        // 将逻辑删除字段的isDeleted改为0
        if (!this.update(new LambdaUpdateWrapper<VehicleOrder>()
                .set(VehicleOrder::getIsDeleted, 0)
                .eq(VehicleOrder::getId, id))) {
            throw new RuntimeException("删除订单失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult getDetails(long id) {
        // 传uid进行权限认证：只有订单用户能操作
        long uid = UserIdHolder.getId();
        OrderDto orderDto =  vehicleOrderMapper.selectDetails(id, uid);
        // 创建时间+10分钟 = 支付截至时间
        orderDto.setPayEndTime(orderDto.getCreateTime().plusMinutes(10));
        return RestResult.success(orderDto);
    }

    @Override
    public RestResult mySellOrder(long uid, Integer orderStatus) {
        List<OrderDto> orderDtoList =  vehicleOrderMapper.mySellOrder(uid, orderStatus);
        return RestResult.success(orderDtoList);
    }
}
